package com.lvmama.controller.rhino.treestatistic;

import com.lvmama.common.result.Result;
import com.lvmama.pojo.dto.rhino.CommonStatisticsSqlVO;
import com.lvmama.pojo.dto.rhino.tree.TreeChartDTO;
import com.lvmama.pojo.entity.rhino.CommonStatisticsResult;
import com.lvmama.pojo.entity.rhino.tree.CodeNode;
import com.lvmama.pojo.entity.rhino.tree.TreeNodeView;
import com.lvmama.service.rhino.treestatistic.TreeStatisticsService;
import com.lvmama.utils.TreeNodeViewUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @param
 * @Title:
 * @Author:wangpeng
 * @Description: TODO(这里用一句话描述这个方法的作用)
 * @return
 * @throws
 */
@RestController
@RequestMapping(value = "/tree")
@Slf4j
public class TreeStatisticsController {
	@Autowired
	private TreeStatisticsService service;

	@PostMapping(value = "queryStructureFlow")
	Result<Map> queryStructureFlow(@RequestBody TreeChartDTO dto){
		log.info("queryStructureFlow start");
		Map returnMap = new HashMap();
		try {
			//校验时间规则：1查询3年前的数据，2开始和结束跨度为3个月
			String mess = TreeNodeViewUtil.checkDate(dto.getBeginDate(), dto.getEndDate());
			if(mess.length()>0){
				returnMap.put("mess", mess);
				return Result.success(returnMap);
			}
			//刷新code码及树节点
			List<CodeNode> codeList = service.queryAllCodeNode();
			TreeNodeViewUtil.refreshCodeList(codeList);
			List<TreeNodeView> nodeList = service.queryAllTreeNodeView();
			TreeNodeViewUtil.refreshNodeList(nodeList);
			//获取根节点，初始化子节点
			TreeNodeView root = TreeNodeViewUtil.getRootTreeNode(dto.getRootNodeId());
			TreeNodeViewUtil.initRootChildrenNodeList(root);
			//根据属性的值域，进行节点的显示名称映射，节点的nodeDesc设置
			//现在是每个节点都映射，其实应该根据root的哪棵树和属性集是否需要映射，来一起判断，决定是否进行映射
			for(TreeNodeView tn : nodeList){//根据属性值，映射所有的属性信息
				String sttr = tn.getAttributeSet();
				String str = "";
				if(null != tn.getAttributeValues() && sttr!=null){
					String[] attrvalues = sttr.split(",");
					String[] values = tn.getAttributeValues().split(",");
					for(int i=0;i<values.length;i++){
						String sttrValue = values[i];
						str = str + TreeNodeViewUtil.treeUtilProperties.getProperty(attrvalues[i]+"."+sttrValue,sttrValue);
					}
				}
				if(tn.getNodeDesc()!=null){
					tn.setNodeDesc(tn.getNodeDesc()+str);//描述加上属性的映射值
				}else{
					tn.setNodeDesc(str);
				}
			}
			//根目录的几个子节点需要把统计值显示出来,占比由于取不到总数，不进行显示：
			List<TreeNodeView> childrenNodeList = root.getChildren();
			if(childrenNodeList!=null && childrenNodeList.size()>0){
				for(TreeNodeView treeNode : childrenNodeList){
					if("N".equals(treeNode.getShowValueFlag())) continue;
					List<CommonStatisticsResult> cCountList = initConditionCommonFS(treeNode,dto,"flow_statistics");
					Double singleCount = Double.valueOf(0);
					if(cCountList.size()>0 ) singleCount = cCountList.get(0).getSumAmount();
					treeNode.setCountValue(TreeNodeViewUtil.doubleToString(singleCount, "0", false));
				}
			}
			returnMap.put("tree", root);
		}catch (Exception e){
			log.error("queryStructureFlow error",e.getMessage(),e);
		}
		log.info("queryStructureFlow end");
		return Result.success(returnMap);
	}

	@PostMapping("queryDataByNode")
	Result<Map> queryDataByNode(@RequestBody TreeChartDTO dto){
		log.info("queryDataByNode start");
		Map map = new HashMap();
		try {
			//得到当前节点的信息
			TreeNodeView treeNodeView = TreeNodeViewUtil.getTreeNodeViewByIdFromCache(dto.getNodeId());
			//根据传入的参数，查询相应的结果集
			List<CommonStatisticsResult> deviceCountList = initConditionCommonFS(treeNodeView,dto,"DeviceCount");
			List<CommonStatisticsResult> netCountList = initConditionCommonFS(treeNodeView,dto,"NetTypeCount");
			List<CommonStatisticsResult> regionCountList = initConditionCommonFS(treeNodeView,dto,"RegionCount");
			//处理流量包中的数据，列表数量及合计.
			Map deviceCountInfo = TreeNodeViewUtil.handleResultListInfo("deviceCountInfo","10",deviceCountList);
			Map netCountInfo = TreeNodeViewUtil.handleResultListInfo("netCountInfo","10",netCountList);
			List<CommonStatisticsResult> netCountList2 = new ArrayList<CommonStatisticsResult>();//过滤不正确的网络运营商
			netCountList.stream().forEach(s->{
				if("NONE".equals(s.getCommonCode())
						||"CM".equals(s.getCommonCode())
						||"CT".equals(s.getCommonCode())
						||"CU".equals(s.getCommonCode())){
					netCountList2.add(s);
				}
			});
			Map regionCountInfo = TreeNodeViewUtil.handleResultListInfo("regionCountInfo","10",regionCountList);//城市显示十条最多的
			//添加设备平台统计数据
			map.put("deviceCount", deviceCountList);
			map.put("deviceCountInfo", deviceCountInfo);
			map.put("netCount", netCountList2);
			map.put("netCountInfo", netCountInfo);
			map.put("regionCount", regionCountList);
			map.put("regionCountInfo", regionCountInfo);
		}catch (Exception e){
			log.error("queryDataByNode error",e.getMessage(),e);
		}
		log.info("queryDataByNode end");
		return Result.success(map);
	}

	@PostMapping("queryChildren")
	Result<TreeNodeView> queryChildrenRateAndCount(@RequestBody TreeChartDTO dto){
		log.info("queryChildrenRateAndCount start");
		TreeNodeView treeNodeView = TreeNodeViewUtil.getTreeNodeViewByIdFromCache(dto.getNodeId());
		try {
			//得到当前节点的信息及其子节点的列表
			List<TreeNodeView> childrenNodeList = TreeNodeViewUtil.getChildrenTreeNodeListByParentIdFromCache(dto.getNodeId());

			//根据此节点查询流量数量totalcount，
			List<CommonStatisticsResult> deviceCountList = new ArrayList<CommonStatisticsResult>();
			CommonStatisticsSqlVO dssvo = TreeNodeViewUtil.initConditionCommonFS(treeNodeView,dto.getBeginDate(),dto.getEndDate(),"flow_statistics");
			deviceCountList = service.queryCommonFS(dssvo);
			Double totalcount = Double.valueOf(0);
			if(deviceCountList.size()>0 ){
				totalcount = deviceCountList.get(0).getSumAmount();
			}
			//循环遍历子节点列表，查询转化率表，得到统计数量，算出百分占比
			//注意一些特殊的节点，如：虚拟节点等
			if(childrenNodeList !=null && childrenNodeList.size( )>0){
				for(TreeNodeView treeNode : childrenNodeList){
					List<CommonStatisticsResult> cCountList = new ArrayList<CommonStatisticsResult>();
					CommonStatisticsSqlVO tssvo = TreeNodeViewUtil.initConditionCommonFS(treeNode,dto.getBeginDate(),dto.getEndDate(),"flow_statistics");
					cCountList = service.queryCommonFS(tssvo);
					Double singleCount = Double.valueOf(0);
					if(cCountList.size()>0 ){
						singleCount = cCountList.get(0).getSumAmount();
					}
					if(singleCount.compareTo(Double.valueOf(0))>0){
						double dou = totalcount.compareTo(Double.valueOf(0)) > 0 ? singleCount/totalcount : 0;
						treeNode.setRateValue(TreeNodeViewUtil.doubleToString(dou, "2", true));
						treeNode.setCountValue(TreeNodeViewUtil.doubleToString(singleCount, "0", false));
					}else{
						treeNode.setRateValue(TreeNodeViewUtil.doubleToString(Double.valueOf(0), "2", true));
						treeNode.setCountValue(TreeNodeViewUtil.doubleToString(singleCount, "0", false));
					}
				}
				treeNodeView.setChildren(childrenNodeList);
				return Result.success(treeNodeView);
			}
		}catch (Exception e){
			log.error("queryChildrenRateAndCount error",e.getMessage(),e);
		}
		log.info("queryChildrenRateAndCount end");
		return Result.success(treeNodeView);
	}

	private List<CommonStatisticsResult> initConditionCommonFS(TreeNodeView tnv,TreeChartDTO dto,String countType){
		List<CommonStatisticsResult> result = new ArrayList<>();
		try {
			CommonStatisticsSqlVO vo =
					TreeNodeViewUtil.initConditionCommonFS(tnv,dto.getBeginDate(),dto.getEndDate(),countType);
			result = service.queryCommonFS(vo);
		}catch (Exception e){
			log.error("initConditionCommonFS",e.getMessage(),e);
		}
		return result;
	}

}
